package _02_linked_list;

import java.util.Iterator;
import java.util.function.Consumer;

/**
 * @author mornd
 * 自定义单向链表<Integer>（带哨兵）
 */
public class SinglySentinelLinkedList implements Iterable<Integer> {
    // 哨兵节点
    private final Node head = new Node(-9527, null);

    public void addFirst(int e) {
        insert(0, e);
    }

    public void add(int e) {
        addLast(e);
    }

    public int get(int index) {
        return getNode(index).value;
    }

    private Node getNode(int index) {
        Node temp = head;
        for (int i = -1; i < index; i++) {
            temp = temp.next;
            if(temp == null) {
                return null;
            }
        }
        return temp;
    }

    public Node getLast() {
        Node p = head;
        while (p.next != null) {
            p = p.next;
        }
        return p;
    }

    private void removeFirst() {
        remove(0);
    }

    public void remove(int index) {
        Node prev = getNode(index - 1);
        Node node = prev.next;
        prev.next = node.next;
    }

    public void insert(int index, int e) {
        Node prev = getNode(index - 1);
        if(prev == null) {
            throw IllegalIndex(index);
        }
        prev.next = new Node(e, prev.next);
    }

    private IllegalArgumentException IllegalIndex(int index) {
        return new IllegalArgumentException(String.format("index [%d] 不合法", index));
    }

    public void addLast(int e) {
        Node lastNode = getLast();
        lastNode.next = new Node(e, null);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (Node p = head.next; p != null; p = p.next) {
            sb.append(p.value);
            if(p.next != null) {
                sb.append(",");
            }
        }
        return sb.append("]").toString();
    }

    /**
     * 返回迭代器
     * @return
     */
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            private Node p = head.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }

            @Override
            public Integer next() {
                Node r = p;
                this.p = r.next;
                return r.value;
            }
        };
    }

    public void foreach(Consumer<Integer> c) {
        Node p = head.next;
        while (p != null) {
            c.accept(p.value);
            p = p.next;
        }
    }

    /**
     * 节点元素
     */
    private static class Node {
        int value;
        Node next;

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }
}
